package com.example.user.customviewdemo.tabviewpager;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;

/**
 * Created by user on 2016/6/21.
 */
public class TabViewPager extends LinearLayout implements RadioGroup.OnCheckedChangeListener,ViewPager.OnPageChangeListener{

    private TabRadioGroup radioGroup;
    private ViewPager viewPager;
    private Context context;

    private ViewPager.OnPageChangeListener onPageChangeListener;
    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener;
    private ViewPagerAdapter adapter;
    private boolean isSmoothScroll = false;

    //用于标记tabs的size和fragments的size是否相等
    private static final int INVALIDE_SIZE = -1;
    private int size = INVALIDE_SIZE;

    public TabViewPager(Context context) {
        super(context);
        init(context);
    }

    public TabViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TabViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        if (context instanceof FragmentActivity){
            FragmentActivity activity = (FragmentActivity) context;
            adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());
        }else {
            throw new ClassCastException("your activity must to extends FragmentActivity!");
        }

        this.setOrientation(LinearLayout.VERTICAL);
        //添加radioGroup
        radioGroup = new TabRadioGroup(context);
        radioGroup.setOrientation(RadioGroup.HORIZONTAL);
        radioGroup.setHasLine(true);
        radioGroup.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        radioGroup.setOnCheckedChangeListener(this);
        this.addView(radioGroup);

        //添加viewpager
        viewPager = new ViewPager(context);
        viewPager.setId(getId()+1); //一定要记到，这里必须要为viewpager设置一个id
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.setMargins(0,50,0,0);
        viewPager.setLayoutParams(layoutParams);
        viewPager.addOnPageChangeListener(this);
        viewPager.setAdapter(adapter);
        this.addView(viewPager);

    }

    /**
     * 设置tab数据
     * @param tabs tab的数据源
     */
    public void setTabs(ArrayList<String> tabs){
        if(tabs == null || tabs.size() == 0){
            return;
        }
        if(this.size != INVALIDE_SIZE && this.size != tabs.size()){
            throw new IllegalArgumentException("your size of tab data must to equals to size of fragment data！你的tabss的size必须等于fragments的size");
        }
        this.size = tabs.size();

        for(int i = 0;i< size;i++){
            radioGroup.addView(createTab(tabs.get(i),i));
        }
    }

    /**
     * 设置ViewPager数据源
     * @param fragments viewpager的数据源
     */
    public void setFragments(ArrayList<Fragment> fragments){
        if(fragments == null || fragments.size() == 0){
            return;
        }
        if(this.size != INVALIDE_SIZE && this.size != fragments.size()){
            throw new IllegalArgumentException("your size of fragment data must to equals to size of tab data！你的fragments的size必须等于tabs的size");
        }
        this.size = fragments.size();

        adapter.setData(fragments);
    }


    /**
     * 产生相同style的radiobutton
     * @param title
     * @return
     */
    private RadioButton createTab(String title,int id){
        RadioButton button = new RadioButton(context);
        button.setSingleLine(true);
        button.setGravity(Gravity.CENTER_HORIZONTAL);
        button.setButtonDrawable(new BitmapDrawable());
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(0,RadioGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.weight = 1;
        button.setLayoutParams(layoutParams);
        button.setPadding(0,10,0,10);
        button.setText(title);
        button.setId(id);
        return button;
    }

    public void setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener onCheckedChangeListener){
        this.onCheckedChangeListener = onCheckedChangeListener;
    }
    public void addOnPageChangedListener(ViewPager.OnPageChangeListener onPageChangeListener){
        this.onPageChangeListener = onPageChangeListener;
    }


    private boolean flag = true;
    private float width = 0;
    private float transX = 0;
    private int state = -1;
    private boolean isBack = false;
    private float prePositionOffset = 0;
    private boolean isScroll = false;

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(this.onCheckedChangeListener != null){
            onCheckedChangeListener.onCheckedChanged(group,checkedId);
        }
        viewPager.setCurrentItem(checkedId,isSmoothScroll);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if(onPageChangeListener != null){
            onPageChangeListener.onPageScrolled(position,positionOffset,positionOffsetPixels);
        }
        if (flag) {
            width = radioGroup.getLineWidth();
            flag = false;
        }

        switch (state) {
            case 0:
                // lineTextview.setTranslationX(position*width);可以使用内嵌view来实现下划线
                radioGroup.setLineOffset(position * width);
                break;
            case 1:
                //lineTextview.setTranslationX(position*width + width*positionOffset);
                radioGroup.setLineOffset(position * width + width * positionOffset);
                break;
            case 2:
                if (positionOffset == 0) {
                    break;
                }
                // lineTextview.setTranslationX(position*width + width*positionOffset);
                radioGroup.setLineOffset(position * width + width * positionOffset);
                break;
        }

    }

    @Override
    public void onPageSelected(int position) {
        if(onPageChangeListener != null){
            onPageChangeListener.onPageSelected(position);
        }
        radioGroup.check(position);

    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if(onPageChangeListener != null){
            onPageChangeListener.onPageScrollStateChanged(state);
        }
        this.state = state;
    }

    /**
     * 设置tab下划线
     * @param isLine 设置tab是否有下划线
     */
    public void setBottomLine(boolean isLine){
        radioGroup.setHasLine(isLine);
    }

    /**
     * 设置tab下划线颜色
     * @param color tab下划线颜色
     */
    public void setBottomLineColor(int color){
        radioGroup.setLineColor(color);
    }

    /**
     * 设置是否缓慢滑动
     * @param isSmoothScroll 当点击tab时，viewpager是否缓慢滑动
     */
    public void setSmoothScroll(boolean isSmoothScroll){
        this.isSmoothScroll = isSmoothScroll;
    }


    /**
     * ViewPager适配器
     */
    static class ViewPagerAdapter extends FragmentPagerAdapter{
        private ArrayList<Fragment> data = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void setData(ArrayList<Fragment> data){
            this.data = data;
            notifyDataSetChanged();
        }
        @Override
        public Fragment getItem(int position) {
            return data.get(position);
        }

        @Override
        public int getCount() {
            return data.size();
        }
    }


    /**
     * 自定义RadioGroup，可设置下划线
     */
    static class TabRadioGroup extends RadioGroup {
        private Paint paint;
        private int lineColor = Color.RED;//默认下划线颜色
        private boolean hasLine;//有没有下划线
        private float offset; //下划线的偏移量
        private float strokeWidth = 5;

        public TabRadioGroup(Context context) {
            super(context);
            init();
        }

        public TabRadioGroup(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        private void init(){
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(lineColor);
            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            paint.setStrokeWidth(strokeWidth);

        }


        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            int count = getChildCount();
            float height = getHeight();
            float lineLength = getWidth() / count; //下划线长度

            //画下划线
            if(hasLine) {
                canvas.drawLine(offset, height-strokeWidth, offset + lineLength, height-strokeWidth, paint);
            }
        }

        /**
         * 设置下滑线颜色
         * @param color
         */
        private void setLineColor(int color){
            this.lineColor = color;
            paint.setColor(color);
            invalidate();
        }

        /**
         * 设置下滑线粗细
         * @param height
         */
        private void setLineHeight(float height){
            this.strokeWidth = height;
            paint.setStrokeWidth(height);
            invalidate();
        }

        /**
         * 设置有无下滑线
         * @param hasLine
         */
        private void setHasLine(boolean hasLine){
            this.hasLine = hasLine;
            invalidate();
        }

        /**
         * 设置下滑线偏移量
         * @param offset
         */
        private void setLineOffset(float offset){
            this.offset = offset;
            invalidate();
        }

        /**
         * 获取下划线长度
         * @return
         */
        private float getLineWidth(){
            float width = getWidth();
            int count = getChildCount();
            if(width == 0){
                throw new RuntimeException("you should call this method at callback method!");
            }
            return  width/count;
        }

    }


}
